<?php

namespace app\models;

use Yii;
use yii\base\Model;

/**
 * LoginForm is the model behind the login form.
 */
class ChangePasswordForm extends Model
{
    public $user_name;
    public $password;
    public $newPassword;
    public $repeatPassword;
    public $verifyCode;

    private $_user = false;

    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            // username and password are both required
            [['password', 'newPassword', 'repeatPassword', 'verifyCode'], 'required'],
            // password is validated by validatePassword()
            ['password', 'validatePassword'],
            //validate the verifyCode
            ['verifyCode','captcha'],
            ['repeatPassword', 'compare','compareAttribute'=>'newPassword'],
        ];
    }
    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'password' => Yii::t('User', 'Old Password'),
            'newPassword' => Yii::t('User', 'New Password'),
            'repeatPassword' => Yii::t('User', 'Repeat Password'),
            'verifyCode' => Yii::t('User', 'VerifyCode'),
       ];
    }



    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validatePassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $user = $this->getUser();
            if (!$user || !$user->validatePassword($this->password)) {
                $this->addError($attribute, yii::t('User', 'Incorrect Old Password.'));
            }
        }
    }

    /**
     * Logs in a user using the provided username and password.
     * @return boolean whether the user is logged in successfully
     */
    public function updatePassword()
    {
        if ($this->validate()) {
            $user = $this->getUser();
            $user->setPassword($this->newPassword);
            $user->repeatpassword = $user->password;
            if($user->update())
            {
                echo '<script>alert("修改密码成功");</script>';
                return true;
            }
            else
            {
                return false;
            }
        }
    }
    /**
     * Finds user by [[username]]
     *
     * @return User|null
     */
    public function getUser()
    {
        if ($this->_user === false) {
            $this->_user = User::findByUsername(yii::$app->user->identity->user_name);
        }
        return $this->_user;
    }
}
